package org.celstec.mobilegame.gameLoaders;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

import org.celstec.mobilegame.server.SubmitGameServiceImpl;
import org.celstec.mobilegame.locatory.Card;
import org.celstec.mobilegame.locatory.CardDropOffZone;
import org.celstec.mobilegame.locatory.CardLocation;
import org.celstec.mobilegame.locatory.Locatory;
import org.jdom.Element;

import com.google.appengine.api.datastore.Key;

public class LocatoryLoader {
	
	public static Locatory load(Element rootElement){
		
		
		Locatory locatory = new Locatory(rootElement.getChild("metadata", LoaderUtil.ns));
		locatory.hm = LoaderUtil.retrieveElementsInHashMap(rootElement, "card", "org.celstec.mobilegame.locatory.Card");
//		locatory.zones  = LoaderUtil.retrieveElementsInVector(rootElement, "cardDropOffZone", "org.celstec.mobilegame.locatory.CardDropOffZone");
//		locatory.locations  = LoaderUtil.retrieveElementsInVector(rootElement, "cardLocation", "org.celstec.mobilegame.locatory.CardLocation");
		Vector<CardDropOffZone> zones  = LoaderUtil.retrieveElementsInVector(rootElement, "cardDropOffZone", "org.celstec.mobilegame.locatory.CardDropOffZone");
		Vector<CardLocation> locations  = LoaderUtil.retrieveElementsInVector(rootElement, "cardLocation", "org.celstec.mobilegame.locatory.CardLocation");

		Iterator itCards = locatory.hm.values().iterator();
		while (itCards.hasNext()) {
//			Card object = (Card) itCards.next();
			SubmitGameServiceImpl.makeObjectPersistent(itCards.next());
		}
	
		for (int i = 0; i < zones.size(); i++) {
			CardDropOffZone zone = zones.get(i);
			zone.locatory = locatory.key;
			zone.card = locatory.hm.get(zone.cardId).key;
			SubmitGameServiceImpl.makeObjectPersistent(zone);
			
		}
		
		for (int i = 0; i < locations.size(); i++) {
			CardLocation loc = locations.get(i);
			loc.locatory = locatory.key;
			loc.card = locatory.hm.get(loc.cardId).key;
			SubmitGameServiceImpl.makeObjectPersistent(loc);

			
		}
		
		locatory.keysZones = new HashSet();
		Iterator<CardDropOffZone> it = zones.iterator();
		while (it.hasNext()) {
			CardDropOffZone z = (CardDropOffZone) it.next();
			locatory.keysZones.add(z.id);
		}
		
		locatory.keysLocations = new HashSet();
		Iterator<CardLocation> it2 = locations.iterator();
		while (it2.hasNext()) {
			CardLocation l = (CardLocation) it2.next();
			locatory.keysLocations.add(l.id);
		}
		
		return locatory;
		
	}

}
